package com.yinhai.message.implement.app.util;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.yinhai.message.api.bean.TMMessage;
import com.yinhai.message.api.bean.TMUser;

public class PushContontrol {

	public static void pushMessage(TMUser user,TMMessage message, String masterSecret, String appkey) throws APIConnectionException, APIRequestException {
		JPushClient jPushClient = new JPushClient(masterSecret,
				appkey, 3);
		PushPayload payload = null;
		payload = buildPushObject(user,message);
		PushResult result = jPushClient.sendPush(payload);
		System.out.println("Got result - " + result);
	}

	/**
	 * 构建发送推送对象
	 * @param user
	 * @return
	 */
	public static PushPayload buildPushObject(TMUser user,TMMessage message) {
		PushPayload.Builder builder = PushPayload.newBuilder();
		builder.setPlatform(Platform.all());
		if(message.isToAlluser()){
			builder.setAudience(Audience.all());
		}else{
			builder.setAudience(Audience.registrationId(user.getRegistrationId()));
		}
		//用下面的方法发送消息不好用
		builder.setNotification(Notification.newBuilder().setAlert(message.getContent()).addPlatformNotification(AndroidNotification.newBuilder().setTitle(message.getTitle()).addExtra("","").build()).build());
		//builder.setNotification(Notification.android("通知消息",message.getTitle(),null)).setMessage(Message.newBuilder().setTitle(message.getTitle()).addExtra("","").setMsgContent(message.getContent()).build());
		builder.setOptions(Options.newBuilder().setApnsProduction(true).build());
		return builder.build();
	}

}
